// createRouter：创建路由实例对象
// createWebHistory：创建history模式路由

import { createRouter, createWebHistory } from 'vue-router'
import Layout from "@/views/Layout/index.vue"


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      component: Layout,
      children: [
        {
          path: "",
          component: () => import('@/views/Home/index.vue')
        },
        {
          path: "category/:id",
          component: () => import('@/views/Category/index.vue')
        },
        {
          path: "category/sub/:id",
          component: () => import('@/views/SubCategory/index.vue')
        },
        {
          path: "detail/:id",
          component: () => import('@/views/Detail/index.vue')
        },
        {
          path: "cart",
          component: () => import('@/views/Cart/index.vue')
        },
        {
          path: "checkout",
          component: () => import('@/views/Checkout/index.vue')
        },
        {
          path: "pay",
          component: () => import('@/views/Pay/index.vue')
        },
        {
          path: "paycallback",
          component: () => import('@/views/Pay/PayBack.vue')
        },
        {
          path: "member",
          component: () => import('@/views/Member/index.vue'),
          children: [
            {
              path: '',
              component: () => import('@/views/Member/components/UserInfo.vue')
            },
            {
              path: "order",
              component: () => import('@/views/Member/components/UserOrder.vue')
            }
          ]
        }
      ]
    },
    {
      path: "/login",
      component: () => import('@/views/Login/index.vue')
    }
    
  ],
  // 滚动到顶部
  scrollBehavior() {
    return { top: 0 }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userInfo = JSON.parse(localStorage.getItem('user'))?.userInfo
  // 判断是否已经登录
  if (userInfo?.token) {
    // 已经登录了不能跳转到登录页
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  // 未登录不能跳转到支付页、订单页、个人中心页
  } else {
    if (to.path === '/checkout' || to.path === '/member' || to.path === '/pay' || to.path === '/paycallback') {
      next('/login')
    } else {
      next()
    }
  }  
})

export default router
